//
//  LoginOperation.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-17.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "LoginOperation.h"
#import "URLFactory.h"
#import "JSON.h"
#import "CoreDataManager.h"
#import "LFAccount.h"
#import "CONSTS.h"


@implementation LoginOperation

@synthesize delegate          =        _delegate;

@synthesize successSel      =          _successSel;
@synthesize failSel         =          _failSel;

- (void)dealloc
{
    [super dealloc];
}

- (id)initWithDelegat:(id)delegate_ successSel:(SEL)successSel_ failSel:(SEL)failSel_
{
    self = [super init];
    if (self) 
    {
        self.delegate = delegate_;
        self.successSel = successSel_;
        self.failSel = failSel_;
    }
    
    return self;
}

- (void)main
{
    //{"api":"com.taobao.wireless.mtop.getLoginUrl","v":"*","ret":["SUCCESS::接口调用成功"],"data":{"key":"26d76cd1-73a3-42fe-be2b-fec9f6611ed6","url":"http://m.taobao.com/mtop/bindApp.htm?token=26d76cd1-73a3-42fe-be2b-fec9f6611ed6"}}
    
    @autoreleasepool 
    {
        CoreDataManager *coreDataManager = [CoreDataManager sharedCoreDataManager];
        /*  因为本程序只支持单个账户管理，所以在登陆新的账户之前清楚coredata中的老账户 */
        [coreDataManager clearAccountCoreData];
        ////////////////////////////////////////////////////////////////
        
        NSString *get_com_taobao_wireless_mtop_getLoginUrl = [URLFactory get_com_taobao_wireless_mtop_getLoginUrl];
        NSError *error = nil;
        NSDictionary *resultDic = [[NSString stringWithContentsOfURL: [NSURL URLWithString: get_com_taobao_wireless_mtop_getLoginUrl] 
                                                            encoding: NSUTF8StringEncoding 
                                                               error: &error] JSONValue];
        
        ITTDINFO(@"%@", resultDic);
        
        if ([self isCancelled]) 
        {
            return;
        }
        
        if (error || !resultDic || [resultDic count] <= 0 || ![[[resultDic objectForKey: @"ret"] objectAtIndex: 0] isEqualToString: SUCCESS])
        {
            if (_delegate && [_delegate respondsToSelector: _failSel]) 
            {
                NSString *reasonFail = [[resultDic objectForKey: @"ret"] objectAtIndex: 0];
                [_delegate performSelectorOnMainThread:_failSel 
                                            withObject: reasonFail 
                                         waitUntilDone:YES];
            }
        }else
        {
            if (_delegate && [_delegate respondsToSelector: _successSel]) 
            {
                NSDictionary *dataDic = [resultDic objectForKey: @"data"];
                //  ITTDINFO(@"%@", dataDic);
                NSString *key = [dataDic objectForKey: @"key"];
                
                //既然需要获取登陆的url，说明这个账户是新的账户，数据库中没有相关的资料,所以就不能在coredata中取，相反要新建一个账户
                LFAccount* account = (LFAccount *)[NSEntityDescription insertNewObjectForEntityForName:@"LFAccount"
                                                                                inManagedObjectContext:[CoreDataManager sharedCoreDataManager].managedObjectContext];
                account.key = key;
                
                
                BOOL saveSign = [coreDataManager saveChangesToCoreData];
                if (!saveSign)  //如果保持失败
                {
                    assert(!saveSign);
                }
                
                NSString *loginUrl = [dataDic objectForKey: @"url"];
                [_delegate performSelectorOnMainThread: _successSel 
                                            withObject: loginUrl 
                                         waitUntilDone: YES];
            }
        }
    }
}



@end
